(function($) {
	var locId = '',userCode = '';
	var sourceData = [];
	var thisDayStr = '',stDateStr = '',endDateStr = '';
	var pageIndex = 1, limit = 200;
	var searchType = 'R';
	var upPullElement = null;
	var isPulling = false;
	var segmentedControl = document.getElementById('segmentedControl');
	$.init({
		swipeBack: true, //启用右滑关闭功能
	});
	$.plusReady(function() {
		baseSetup();
		
		var _self = plus.webview.currentWebview();
		_self.setStyle({
			popGesture: 'none'  // 作用于ios 禁止右滑关闭
		});
	});

	function getHuiZhenList() {
		if (isPulling == true) {
			upPullElement.endPullUpToRefresh(false);
			return;
		}
		isPulling = true;
		//改为按日查询了
		plus.nativeUI.showWaiting("正在查询",{modal:false});
		var pdict = {
			userCode:userCode,
			LocID:'',
			StartDate:stDateStr,
			EndDate:endDateStr,
			conStatus:'',
			QryType:searchType
		}
		//userCode As %String, LocID As %String, StartDate As %String, EndDate As %String, conStatus As %String, QryType
		//var pdict = {'parr':pageIndex+'^'+ limit +'^' + stDateStr + '^' + endDateStr + '^' + locId + '^' + searchType }
		var paramDict = {'method':'web.DHCEMConsInterface:QryDocCstList',
			'params':JSON.stringify(pdict),'type':'Query'}
		// console.log(JSON.stringify(pdict));
		mui.DHCWebService(paramDict, function(result) {
			// console.log(JSON.stringify(result));
			plus.nativeUI.closeWaiting();
			if (result.msgcode != '1') {
				mui.toast(result.msg)
				upPullElement.endPullUpToRefresh(false);
				isPulling = false;
				return
			}
			var dataArr = result.data
			for (var i = 0; i < dataArr.length;i++) {
				var oneDict = dataArr[i];
				if (oneDict == null || oneDict == '') {
					continue;
				} 
				sourceData.push(oneDict); 
			}			
			updateTableView(dataArr);
			upPullElement.endPullUpToRefresh(dataArr.length<limit);
			pageIndex++;
			isPulling = false;
		}, function(errorStr) {
			mui.toast(errorStr);
			plus.nativeUI.closeWaiting();
			upPullElement.endPullUpToRefresh(false);
			isPulling = false;
		});
	}
	
	function updateTableView(dataArr) {
		var tableView = document.getElementById('tableView');
		var lis = tableView.querySelectorAll('li');
		var oldLength = lis.length;
		for(var i = 0; i < dataArr.length; i++) {
			var oneDict = dataArr[i];
			if (oneDict == null || oneDict == '') {
				continue;
			}
			var oneLi = document.createElement('li');
			oneLi.setAttribute('class', 'mui-table-view-cell');
			oneLi.id = 'li-' + (oldLength + i);
			tableView.appendChild(oneLi);
			var titleStr = oneDict['PatBed'] + '床&nbsp;' + oneDict['PatName'];
			var diag = dealSepcialCharacter(oneDict['PatDiagDesc']).replace(/;/g, '');
			var apptime = '&nbsp&nbsp'+oneDict['CstRDate']+' '+oneDict['CstRTime'];
			var applyer = oneDict['CstRUser']+apptime;
			var asker = oneDict['CsUser'] +'&nbsp;&nbsp;'+oneDict['CstNDate'] +'&nbsp;'+oneDict['CstNTime'];
			
			var contime = ''//'&nbsp&nbsp'+oneDict['CstNDate']+' '+oneDict['CstNTime'];
			if (oneDict['CstNDate'] == '') {
				contime = '';
			}
			var inout = oneDict['CstOutFlag']=='N'?'院内':'院外'
			if (oneDict['CstOutFlag'] == '') {
				inout = ''
			}
			var coner = oneDict['CsUser']+contime;
			oneLi.innerHTML = '<div class="title">'+
				'<span class="bedNum">'+oneDict['PatBed']+'床</span>'+
				'<span class="patName">'+oneDict['PatName']+'</span>'+diag+'</div>'+
				'<span class="label">申请护士：</span>'+
				'<span class="labelKey">'+applyer+'</span><br />'+
				'<span class="label">要求会诊：</span>'+
				'<span class="labelKey">'+asker+'</span><br />'+
				'<span class="label">会诊护士：</span>'+
				'<span class="labelKey">'+coner+'</span><br />'+
				'<span class="label">会诊科室：</span>'+
				'<span class="labelKey">'+oneDict['CsLocDesc']+'</span><br />'+
				'<div class="posLabel"><div class="state">'+oneDict['CsStatDesc']+'</div>'+
				'<div class="inoutTip">'+inout+'</div>'+
				'<div class="typeTip">'+oneDict['CstType']+'</div></div>';
			oneLi.addEventListener('tap',openHuiZhenDetailPage,false);
		}
	}
	
	function openHuiZhenDetailPage() {
		var idArr = this.id.split('-');
		var index = parseInt(idArr[1]);
		var oneDict = sourceData[index];
		mui.openWindow({
			url: "huizhen-detail.html",
			id: "huizhen-detail",
			extras: {
				sourceData: oneDict
			},
			waiting: {
				autoShow: false, //自动显示等待框，默认为true
			}
		});
	}
	
	function updateYearMonthAndWeek(dayStr){
		var yearMonth = document.getElementById('yearMonth');
		yearMonth.innerText = dayStr;
		stDateStr = dayStr;
		endDateStr = dayStr;
		// return
		// var arr = getStEndDateWeek(dayStr);
		// stDateStr = arr[0];
		// endDateStr = arr[1];
		// var currWeek = document.getElementById('currWeek');
		// currWeek.innerText = arr[2];
		// var yearMonth = document.getElementById('yearMonth');
		// yearMonth.innerText = endDateStr.substring(0,endDateStr.length);
		resetPullRefresh();
	}

	function selectHuiZhenMonth() {
		var _self = this;
		if(_self.picker) {
			_self.picker.show(function(rs) {
				_self.innerText = rs.text;
				updateYearMonthAndWeek(rs.text);
				_self.picker.dispose();
				_self.picker = null;
				
			});
		} else {
			var optionsJson = '{"type":"date"}';
			var options = JSON.parse(optionsJson);
			_self.picker = new mui.DtPicker(options);
			_self.picker.show(function(rs) {
				_self.innerText = rs.text;
				updateYearMonthAndWeek(rs.text);
				_self.picker.dispose();
				_self.picker = null;
			});
		}
	}
	function iOSSelectHuiZhenMonth() {
		var _self = this;
		plus.nativeUI.pickDate(function(e) {
			var d = e.date;
			var dateStr = d.getFullYear()+'-'
			if (d.getMonth() < 9) {
				dateStr += '0'
			}
			dateStr += (d.getMonth() + 1)+'-'
			if (d.getDate() < 10) {
				dateStr += '0'
			}
			dateStr += d.getDate()
			_self.innerText = dateStr
			updateYearMonthAndWeek(dateStr);
		}, function(e) {}, {});
		
	}
	function baseSetup(){
		$('.mui-scroll-wrapper').scroll({
			indicators: false //是否显示滚动条
		});
		plus.navigator.setStatusBarBackground('#24af96');
		plus.navigator.setStatusBarStyle('light');
		mui.back = function() {
			plus.navigator.setStatusBarBackground('#fff')
			plus.navigator.setStatusBarStyle('dark');
			var _self = plus.webview.currentWebview();
			_self.close("auto");
		}
		var perInfo = app.getState()
		if(perInfo) {
			// console.log(JSON.stringify(perInfo));
			locId = perInfo.loginWardId //currentLoc['LocId'];
			userCode = perInfo.loginCode
		} else {
			mui.toast('用户未登录');
			plus.nativeUI.closeWaiting()
			var state = {};
			app.setState(state);
			localStorage.setItem('$user', JSON.stringify(state));
			plus.runtime.restart(); //重新启动
			return;
		}
		var scrolls = document.querySelectorAll('.mui-slider-group .mui-scroll')
		mui.each(scrolls,function(index, pullRefreshEl){
			mui(pullRefreshEl).pullToRefresh({
				up: {
					callback: function() {
						upPullElement = this;
						getHuiZhenList();
					}
				}
			});
		});
		mui('#slider').slider().stopped = true; //禁止左右滑动
		thisDayStr = getTodayStr();
		// console.log(thisDayStr)
		updateYearMonthAndWeek(thisDayStr);
		var yearMonth = document.getElementById('yearMonth');
		if (plus.os.name == 'iOS') {
			yearMonth.addEventListener('tap', iOSSelectHuiZhenMonth, false);
		}else{
			yearMonth.addEventListener('tap', selectHuiZhenMonth, false);
		}
		
		var lastWeek = document.getElementById('lastWeek');
		lastWeek.addEventListener('tap', function() {
			var lastDay = getLastDay(stDateStr);
			updateYearMonthAndWeek(lastDay);
		}, false);
		var nextWeek = document.getElementById('nextWeek');
		nextWeek.addEventListener('tap', function() {
			var nextDay = getNextDay(endDateStr);
			updateYearMonthAndWeek(nextDay);
		}, false);
		
		var thisWeek = document.getElementById('thisWeek');
		thisWeek.addEventListener('tap', function() {
			updateYearMonthAndWeek(thisDayStr);
		}, false);
		//seg点击切换
		var controls = segmentedControl.querySelectorAll('.mui-control-item');
		for (var i = 0; i < controls.length;i++) {
			var oneControl = controls[i];
			oneControl.addEventListener('tap',function(){
				searchType = this.getAttribute('data-type');
				resetPullRefresh()
			});
		}
		
	}
	function resetPullRefresh (){
		var tableView = document.getElementById('tableView');
		tableView.innerHTML = '';
		pageIndex = 1;
		sourceData.splice(0,sourceData.length);
		mui('#pullrefresh').scroll().scrollTo(0,0,100);
		if(upPullElement != null){
			upPullElement.refresh(true);
		}
		getHuiZhenList();
	}
	function dealSepcialCharacter(str){
		var valueStr = str;
		if (str == undefined) {
			return valueStr
		}
		valueStr = valueStr.replace(/ /g, '&nbsp;');
		valueStr = valueStr.replace(/@and@/g, '&');
		valueStr = valueStr.replace(/@《@/g,'<');
		valueStr = valueStr.replace(/@》@/g,'>');
		valueStr = valueStr.replace(/@jianhao@/g,'^');
		valueStr = valueStr.replace(/@br@/g, '<br />');
		return valueStr;
	}
})(mui);
/*
 * {
	'ConsultId': '713762', 会诊 id
	'EpisodeId': '31171749',就诊 id
	'Diag': 'DIAG@腹水',病人诊断
	'patname': '杨淑珍',病人姓名
	'bedcode': '26',床号
	'RegNo': '45930290',登记号
	'Bah': '2523129',病案号
	'appdate': '2020-01-17',会诊申请日期
	'appdoc': '徐娜',申请人
	'apptime': '08:58',会诊申请时间
	'attitude': '',会诊意见
	'condestinat': '',简要病历及会诊目的
	'consultdate': '2020-01-18',会诊日期
	'condep': '神经内科',会诊科室
	'condoc': '尹翮翔',会诊医生
	'contime': '10:56',会诊时间
	'InOut': '院内',申请院内院外
	'status': '执行',会诊状态
	'typ': '普通',申请类型
	'RequestConDoc': '',要求会诊医生
	'RequireDate': ''要求会诊日期
}
 */